package com.shanxia.codec.cmd;

import com.shanxia.codec.ProtocolDataBase;
import com.shanxia.codec.enums.DecodeEnum;
import lombok.Data;

import java.util.Arrays;

import static com.shanxia.codec.Decoder.*;

/**
 * C -> S
 * 充电桩对后台下发的充电桩开启充电控制应答
 * 充电桩对后台下发的充电桩开启充电控制报文应答
 */
@Data
public class Cmd8 extends ProtocolDataBase {

    public static final int MIN_SIZE = 73;

    private int v1;
    private int v2;
    private String sn;                        //充电桩编码
    private int pilePort;                    //充电枪口: 只有一机一桩此参数可为 0，多枪编号从 1 开始
    private int code;                        //设置/查询 结果
    private String serial;                    //充电流水号

    public Cmd8(){
        super.setCmd(8);
    }

    public static Cmd8 decodeFromBase(ProtocolDataBase protocolDataBase) {
        Cmd8 cmd = new Cmd8();
        cmd.copyDataFrom(protocolDataBase);
        byte[] dataField = protocolDataBase.getDataField();
        //数据域长度
        if (dataField.length < MIN_SIZE) {
            cmd.setResult(DecodeEnum.InvalidData);
            return cmd;
        }
        int offset = 0;
        cmd.v1 = getUint16(dataField, offset);
        offset += 2;
        cmd.v2 = getUint16(dataField, offset);
        offset += 2;
        // 32字节充电桩编码
        cmd.sn = byteToAscii(Arrays.copyOfRange(dataField, offset, offset + 32), true);
        offset += 32;
        // 1字节充电枪口
        cmd.pilePort = getUint8(dataField[offset++]);
        // 4字节命令执行结果
        cmd.code = getInt32(dataField, offset);
        offset += 4;
        // 32字节充电流水号
        cmd.serial = byteToAscii(Arrays.copyOfRange(dataField, offset, offset + 32), true);
        return cmd;
    }

    @Override
    public String toString() {

        StringBuffer buffer = new StringBuffer();
        buffer.append("#cmd8#").append("\n");
        buffer.append("v1:").append(v1).append("\n");
        buffer.append("v2:").append(v2).append("\n");
        buffer.append("充电桩编码:").append(sn).append("\n");
        buffer.append("充电枪口:").append(pilePort).append("\n");
        buffer.append("充电流水号:").append(serial).append("\n");
        buffer.append("命令执行结果:").append(code).append("\n");
        return buffer.toString();
    }
}
